import { size, Size, v3, Vec3, view } from 'cc';

import { UIConfig } from '../define/UIConfig';
import Train from './Train';

/**
 * 瓦块节点位置管理器
 */
export default class TileModel {

    // 单例
    private static _ins: TileModel = null;
    private constructor() {
        this.initPosList();
    }
    public static getIns(): TileModel {
        if (!TileModel._ins)
            TileModel._ins = new TileModel();
        return TileModel._ins;
    }

    // 坐标合集
    private _posList: Vec3[][] = null;
    /** 初始化色块位置表 */
    private initPosList() {
        this._posList = [];

        for (let x = 0; x < UIConfig.COL; x++) {
            this._posList[x] = [];
            const posX = this.beginX + x * (UIConfig.WIDTH + UIConfig.SPACE);

            for (let y = 0; y < UIConfig.ROW; y++) {
                const posY = this.beginY + y * (UIConfig.WIDTH + UIConfig.SPACE);
                this._posList[x][y] = v3(posX, posY);
            }
        }
    }

    /**
     * 容器预期宽度
     */
    public get width(): number {
        if (this._width === undefined) {
            this._width = (UIConfig.PADDING * 2) + (UIConfig.WIDTH * UIConfig.COL) + (UIConfig.SPACE * (UIConfig.COL - 1));
            if (view.getDesignResolutionSize().width < this._width)
                console.warn("[TileCtrl] 容器超宽！width:", this._width);
        }
        return this._width;
    }
    private _width: number = undefined;

    /**
     * 容器预期高度
     */
    public get height(): number {
        if (this._height === undefined) {
            this._height = (UIConfig.PADDING * 2) + (UIConfig.WIDTH * UIConfig.ROW) + (UIConfig.SPACE * (UIConfig.ROW - 1));
            if (view.getDesignResolutionSize().height < this._height)
                console.warn("[TileCtrl] 容器超高！height:", this._height);
        }
        return this._height;
    }
    private _height: number = undefined;

    /** 消除UI底板尺寸 */
    public static get size(): Size {
        return size(TileModel.getIns().width, TileModel.getIns().height);
    }

    /**
     * 起始横（首列）坐标
     */
    public get beginX(): number {
        if (this._beginX === undefined) {
            this._beginX = -(this.width / 2) + UIConfig.PADDING + (UIConfig.WIDTH / 2);
        }
        return this._beginX;
    }
    private _beginX: number = undefined;

    /**
     * 起始纵（首行）坐标
     */
    public get beginY(): number {
        if (this._beginY === undefined) {
            this._beginY = -(this.height / 2) + UIConfig.PADDING + (UIConfig.WIDTH / 2);
        }
        return this._beginY;
    }
    private _beginY: number = undefined;

    /**
     * 获取指定行列坐标，对应瓦块节点的位置
     * @param x [number | Train] 列(横)坐标 | 瓦块节点的行列对象
     * @param y [number] 行(纵)坐标
     * @returns 
     */
    public static getPos(x: number | Train, y?: number): Vec3 {
        if (typeof x === 'number')
            return TileModel.getIns()._posList[x][y] || Vec3.ZERO;
        else
            return TileModel.getIns()._posList[x.x][x.y] || Vec3.ZERO;
    }

}